package com.gnerv.battle.boot.module.dynamic.datasource.service.impl;

import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.creator.DataSourceProperty;
import com.baomidou.dynamic.datasource.creator.DefaultDataSourceCreator;
import com.gnerv.battle.boot.module.dynamic.datasource.service.DynamicDatasourceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.datasource.init.ScriptUtils;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @author Gnerv LiGen
 */
@Slf4j
@Service
public class DynamicDatasourceServiceImpl implements DynamicDatasourceService {

    private final DynamicRoutingDataSource dynamicRoutingDataSource;
    private final DefaultDataSourceCreator dataSourceCreator;

    public DynamicDatasourceServiceImpl(DataSource dataSource, DefaultDataSourceCreator dataSourceCreator) {
        this.dynamicRoutingDataSource = (DynamicRoutingDataSource) dataSource;
        this.dataSourceCreator = dataSourceCreator;
    }

    @Override
    public boolean create(DataSourceProperty dataSourceProperty) {
        DataSource dataSource = dataSourceCreator.createDataSource(dataSourceProperty);
        dynamicRoutingDataSource.addDataSource(dataSourceProperty.getPoolName(), dataSource);
        return true;
    }

    @Override
    public boolean delete(String code) {
        dynamicRoutingDataSource.removeDataSource(code);
        return true;
    }

    @Override
    public boolean update(DataSourceProperty dataSourceProperty) {
        DataSource dataSource = dataSourceCreator.createDataSource(dataSourceProperty);
        dynamicRoutingDataSource.addDataSource(dataSourceProperty.getPoolName(), dataSource);
        return true;
    }

    @Override
    public DataSource select(String code) {
        return dynamicRoutingDataSource.getDataSource(code);
    }

    @Override
    public boolean initSql(String code, Resource resource) {
        DataSource dataSource = dynamicRoutingDataSource.getDataSource(code);
        try {
            ScriptUtils.executeSqlScript(dataSource.getConnection(), resource);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return true;
    }

    @Override
    public boolean inspect(DataSourceProperty dataSourceProperty) {
        DataSource ds = dataSourceCreator.createDataSource(dataSourceProperty);
        try {
            Connection connection = ds.getConnection();
            connection.close();
        } catch (SQLException e) {
            return false;
        }
        return true;
    }
}
